package com.showsu.editor.utils.remote;

import cn.hutool.http.HttpUtil;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.showsu.editor.entity.platform.xhs.XhsAwemeDetailResult;
import com.showsu.editor.enums.SuccessEnum;
import com.showsu.editor.service.IRemoteInterfaceRecordService;
import com.showsu.editor.service.IRemoteInterfaceWarnSmsRecordService;
import com.showsu.editor.utils.Constant;
import com.showsu.editor.utils.GsonFailSafeArrayJsonDeserializer;
import com.showsu.editor.utils.RetryUtils;
import com.showsu.editor.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.lang.reflect.Type;
import java.util.List;
import java.util.concurrent.Callable;

/**
 * @Author: William
 * @Description:
 * @Date: Created in 10:40 下午 2023/12/25
 * @Modified By:
 */
@Slf4j
@Component
public class DataShopUtil {

    @Value("${dataShopAPI.url}")
    private String dataShopUrl;

    @Value("${dataShopAPI.token}")
    private String dataShopToken;

    private static final int timeout = 30000;

    /**
     * 最多重试次数
     */
    private static final int RETRY_MAX_COUNT = 3;

    /**
     * 重试等待间隔
     */
    private static final int RETRY_WAIT_TIME = 1500;

    private static final Integer pageSize = 20;
    private static final Integer totalLimit = 60;

    /**
     * gson反序列化时，用于忽略array的错误。因为有的时候字段返回为空，我们认为是可以接受的。
     */
    private GsonFailSafeArrayJsonDeserializer gsonFailSafeArrayJsonDeserializer = new GsonFailSafeArrayJsonDeserializer();

    @Autowired
    private IRemoteInterfaceRecordService remoteInterfaceRecordService;

    @Autowired
    private IRemoteInterfaceWarnSmsRecordService remoteInterfaceWarnSmsRecordService;

    /**
     * 查询xhs笔记详情
     * https://apifox.com/apidoc/shared-2e325282-e366-4f77-b092-b58850245a5f/api-95435404?pwd=AIX2yWA0
     * @param noteId
     * @return
     */
    public XhsAwemeDetailResult getXhsAwemeDetail(String noteId, Long interfaceId) {
        if (StringUtils.isBlank(noteId)) {
            return null;
        }
        Type type = new TypeToken<XhsAwemeDetailResult>(){}.getType();
        Gson gson = new GsonBuilder().registerTypeAdapter(List.class, gsonFailSafeArrayJsonDeserializer).create();
        XhsAwemeDetailResult result = new XhsAwemeDetailResult();
        String response = RetryUtils.retry(new Callable<String>() {
            @Override
            public String call() {
                try {
                    long start = System.currentTimeMillis();
                    StringBuilder url = new StringBuilder(dataShopUrl).append("/api/xiaohongshu/get-note-detail/v1?token=")
                            .append(dataShopToken).append("&noteId=").append(noteId);
                    String responseInner = HttpUtil.get(url.toString(), timeout);
                    log.info("DataShopUtil查询xhs作品详情-响应耗时:{}-noteId:{}", System.currentTimeMillis() - start, noteId);
                    XhsAwemeDetailResult temp = gson.fromJson(responseInner, type);
                    if (temp != null
                            && (Constant.containsXhsAwemeNotExistHint(StringUtil.convertUnicodeToChinese(temp.getMsg()))
                                || (temp.getData() != null
                                    && (Constant.containsXhsAwemeNotExistHint(StringUtil.convertUnicodeToChinese(temp.getData().getMsg()))
                                        || Constant.containsXhsAwemeNotExistHint(StringUtil.convertUnicodeToChinese(temp.getData().get_msg()))
                                        )
                                    )
                           )
                    ) {
                        remoteInterfaceRecordService.add(interfaceId, SuccessEnum.SUCCESS.getCode());
                        return Constant.xhsAwemeNotExist2;
                    }
                    //如果平台那边报错再重试一次
                    if (temp == null || (temp != null && temp.getCode() != null && temp.getCode().intValue() != 0)) {
                        remoteInterfaceRecordService.add(interfaceId, SuccessEnum.FAIL.getCode());
                        return "";
                    }
                    remoteInterfaceRecordService.add(interfaceId, SuccessEnum.SUCCESS.getCode());
                    return responseInner;
                } catch (Exception e) {
                    remoteInterfaceRecordService.add(interfaceId, SuccessEnum.FAIL.getCode());
                    log.error("DataShopUtil.getXhsAwemeDetail(String) error, noteId:{}, e:{}", noteId, e);
                    return "";
                }
            }
        }, RETRY_MAX_COUNT, RETRY_WAIT_TIME);
        if (StringUtils.isBlank(response)) {
            remoteInterfaceWarnSmsRecordService.sendWarnSmsIn15mins(interfaceId,
                    new StringBuilder("noteId=").append(noteId).toString());
            return result;
        }
        if (response.equals(Constant.xhsAwemeNotExist2)) {
            return null;
        }
        try {
            result = gson.fromJson(response, type);
        } catch (Exception e) {
            log.error("DataShopUtil.getXhsAwemeDetail(String) convert error, noteId:{}, e:{}", noteId, e);
        }
        return result;
    }


    public static void main(String[] args) {
        //String response = HttpUtil.get("http://52.83.102.195:8008/api/xiaohongshu-pgy/get-kol-fans-portrait/v1?token=YsiaBlgz&kolId=63abd6600000000026006fd2");
        //String response = HttpUtil.get("http://52.83.102.195:8008/api/xiaohongshu/get-user/v2?token=YsiaBlgz&userId=61a750c8000000001000cc19");
        String response = HttpUtil.get("http://52.83.102.195:8008/api/xiaohongshu/get-note-detail/v1?token=YsiaBlgz&noteId=65eefc2700000000120219c2");
        System.out.println(response);
        Type type = new TypeToken<XhsAwemeDetailResult>(){}.getType();
        //Gson gson = new Gson();
        GsonFailSafeArrayJsonDeserializer gsonFailSafeArrayJsonDeserializer0 = new GsonFailSafeArrayJsonDeserializer();
        Gson gson = new GsonBuilder().registerTypeAdapter(List.class, gsonFailSafeArrayJsonDeserializer0).create();
        XhsAwemeDetailResult result = gson.fromJson(response, type);
        System.out.println("111");
    }
}
